from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class JSONRequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 1. 获取请求路径
        print(f"收到请求路径: {self.path}")

        # 2. 获取内容长度
        content_length = int(self.headers.get('Content-Length', 0))
        # 3. 读取请求体
        body = self.rfile.read(content_length)
        
        try:
            # 4. 解码并解析 JSON
            json_data = json.loads(body.decode('utf-8'))
            print("接收到的 JSON 数据:", json_data)

            # 5. 构造响应
            response = {
                "message": "JSON received successfully",
                "your_data": json_data,
                "echo": "Hello from server!"
            }
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response, ensure_ascii=False, indent=2).encode('utf-8'))

        except json.JSONDecodeError as e:
            # 如果 JSON 格式错误
            error_response = {
                "error": "Invalid JSON",
                "message": str(e)
            }
            self.send_response(400)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(error_response).encode('utf-8'))

    def do_GET(self):
        # 可选：处理 GET 请求
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        response = {"message": "Send POST with JSON body to /"}
        self.wfile.write(json.dumps(response).encode('utf-8'))


# 启动服务器
def run_server(port=8000):
    server_address = ('', port)  # 监听所有接口
    httpd = HTTPServer(server_address, JSONRequestHandler)
    print(f"服务器启动在 http://localhost:{port}")
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()